package com.huawei.classroom.student.h18;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.FieldPosition;
import java.util.Properties;
import java.lang.reflect.Field;

public class MyClassFactory {
	private static Properties read_ini = new Properties();
	//我喜欢
	public MyClassFactory(String path) {
		Reader reader = null;
		try {
			reader = new InputStreamReader(new FileInputStream(path), "UTF-8");//按编码读文件
			read_ini.load(reader);//得到键值对
		}catch(IOException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}finally {
			close(reader);
		}
	}
	//关闭输入流
	private void close(Closeable inout) {
		if (inout != null) {
			try {
				inout.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	//动态创建类
	public <T>T createInstance(Class clazz) {//<T>T是让函数返回输入的类型
		Object obj = null;
		try {
			obj = clazz.newInstance();
			String name = clazz.getName();
			Field[] field = clazz.getDeclaredFields();//clazz的属性数组
			for(int i=0; i<field.length; i++) {
				field[i].setAccessible(true);//允许访问private类型
				String className = clazz.getName();
				String value = read_ini.getProperty(className + "." +field[i].getName());
				if(value.charAt(0) == '\"') {
					value = value.replace("\"", "");
					field[i].set(obj, value);//对属性赋值
				}
				else {
					field[i].set(obj, Integer.parseInt(value));
				}
				field[i].setAccessible(false);//关闭权限
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return (T)obj;
	}
	
}
